/**
 * Created by Lcp on 2018/5/29.
 */
//画版工具
var canvas = window.parent.document.getElementById('canvas' + window.parent.nowIndex),
   ctx = canvas.getContext('2d'),
   reg = canvas.toDataURL('image/png',1);
drawCanvas(reg,'bigImg');
function drawCanvas(src,id){
    var image = new Image(),
        canvas = document.createElement("canvas");
    image.src = src;
    var heights = $('#yulan').height() - 39,
        widths = $('#yulan').width(),
        rate = 1;
    image.onload = function(){

        //防止小图放大 大图等比例缩小
        if(image.width > widths && image.height > heights){
            if(image.width / widths > image.height /heights){
                rate = image.width / widths;
            }else{
                rate = image.height / heights;
            }
        }else{
            if(image.width > widths){
                rate = image.width / widths;
            }
            if(image.height > heights){
                rate = image.height / heights;
            }
        }
        canvas.width = image.width;
        canvas.height = image.height;
        if(image.height < $('.bigImg').height()){
            canvas.style.marginTop = (($('.bigImg').height() - image.height) / 2).toFixed(2) + 'px';
        }
        $('#' + id).html(canvas);
        var width = canvas.width;
        var height = canvas.height;
        var obj = canvas.getContext("2d");
        obj.drawImage(image, 0 ,0 ,width,height);
        var typechoose = $(".tools .toolList");
        var poly=$(".poly");
        //var bian=$(".bian");
        var polychoose=$(".bian");
        var shezhi=$(".shezhi");
        var cut=$(".cut");
        var copy=$(".copy");
        var back=$(".back");
        var clear=$(".clear");
        var save=$(".save");
        var create=$(".create");
        var xinjian=$(".xinjian");
        var create_close=$(".xinjian_before");
        var cutflag=false;
        var iscut=true;
        var color="#ff0000";
        var type="circle";
        var n=3;
        var linewidth="1";
        var style="stroke";
        var arr = [];
        arr.push(obj.getImageData(0,0,width,height));
        // 绘制形状
        typechoose.each(function(index,ele){
            $(ele).click(function(){
                type = $(this).attr("data");
                if($(this).is(".lines")||$(this).is(".pen")){
                    style="stroke";
                }
            })
        });
// 剪切
        cut.click(function(){
            type=$(this).attr("data");
            typechoose.removeClass("typeactive");
            $(this).css({color:"#5bd219",backgroundColor:"#fff"}).toggleClass("shezhistyle");
            iscut=true;
        })
        copy.click(function(){
            type="cut";
            typechoose.removeClass("typeactive");
            $(this).css({color:"#5bd219"}).toggleClass("shezhistyle");
            iscut=false;
        })
// 设置
        shezhi.each(function(index,ele){
            if($(ele).is(".cut")||$(ele).is(".copy")){
                return;
            }else{
                $(ele).click(function(){
                    $(this).css({color:"#5bd219"}).animate({opacity:0.99},200,function(){
                        $(this).css({color:"#fff",opacity:1});
                    });
                })
            }
        })
// 撤销
        back.click(function(){
            if(arr.length > 1){
                arr.pop();
                obj.clearRect(0,0,width,height);
                if(arr.length > 0){
                    obj.putImageData(arr[arr.length-1],0,0,0,0,width,height);
                }
            }
        })
// 清除
        clear.click(function(){
            arr=[];
            obj.clearRect(0,0,width,height);
        })
// 保存
        save.click(function(){
            //图片预览 有压缩 现在复原
            var reg = canvas.toDataURL("image/png",1);//跳转页面手动保存
            window.parent.sendMsg[window.parent.nowIndex] = reg;
            window.parent.drawCanvas(window.parent.sendMsg[window.parent.nowIndex],window.parent.nowIndex);
        })

//多边形边数
        polychoose.change(function(){
            n = this.value;
        })
        var x,y,ww,hh,lx,ly,lw,lh,cutdata;
        canvas.onmousedown = function(event){
            var e = event || window.event;
            x = e.offsetX;
            y = e.offsetY;
            if(type == "pen"){
                obj.beginPath();
                obj.moveTo(x,y);
            }
            if(type == "eraser"){
                obj.clearRect(x-5,y-5,10,10);
            }
            if(cutflag&&type=="cut"){
                if(arr.length!=0){
                    arr.splice(-1,1);
                }
            }
            var draw = new Draw(obj,{type:style,color:color,width:linewidth});//实例化构造函数
            canvas.onmousemove = function(event){
                var e = event || window.event;
                ww = e.offsetX;
                hh = e.offsetY;
                if(type != "eraser"){
                    obj.clearRect(0,0,width,height);
                    obj.drawImage(image, 0 ,0 ,width,height);
                    if(arr.length != 0){
                        obj.putImageData(arr[arr.length-1],0,0,0,0,width,height);
                    }
                }
                if(cutflag && type=="cut"){
                    if(iscut){
                        obj.clearRect(lx,ly,lw-lx,lh-ly);
                    }
                    var nx=lx+(ww-x);
                    var ny=ly+(hh-y);
                    obj.putImageData(cutdata,nx,ny);
                }else if(type=="poly"){
                    draw[type](x,y,ww,hh,n);
                }else{
                    /*删除以后找不到type类型*/
                    draw[$('.tools').find('.toolActive').attr('data')](x,y,ww,hh);
                    //    draw[type](x,y,ww,hh);
                }

            }
            document.onmouseup=function(){
                canvas.onmousemove=null;
                document.onmouseup=null;
                if(type=="cut"){
                    if(!cutflag){
                        cutflag=true;
                        cutdata=obj.getImageData(x+1,y+1,ww-x-2,hh-y-2);
                        lx=x;ly=y;lw=ww;lh=hh;
                    }else{
                        cutflag = false;
                    }
                }
                arr.push(obj.getImageData(0,0,width,height));
            }
            canvas.onclick = function(event){
                console.log(type);
                if(type == 'pen'){
                    var e = event || window.event,
                        x = e.clientX,//鼠标距浏览器位置
                        y = e.clientY,
                        resetX = e.offsetX,
                        resetY = e.offsetY,//鼠标在canvas中位值
                        canvasX = $(canvas).offset().left,
                        canvasY =  $(canvas).offset().top,
                        inputX = 0,
                        inputY = 0,//文本框位置
                        input = document.createElement('input');
                    if(canvas.height + canvasY - y < 34){
                        inputY = 2 * y - canvas.height - canvasY - 34; //往上移动5px
                    }else{
                        inputY = y;
                    }
                    if(canvas.width + canvasX - x < 100){
                        inputX = 2 * x - canvas.width - canvasX - 100; //往左移动5px
                    }else{
                        inputX = x;
                    }
                    if(canvas.width - resetX < 100){
                        resetX = canvas.width - 100;
                    }
                    if(canvas.height - resetY < 34){
                        resetY = canvas.height - 34;
                    }
                    $(input).css({position: 'fixed',left: inputX,top: inputY,width: '100px',height: '34px',border: '1px dashed #ccc',color: 'red',fontSize: '12px',background:'transparent'});
                    $(input).attr('placeholder','请输入内容');
                    $(input).attr('maxLength','10');
                    $(input).attr('id','textInput');
                    $('body').append(input);
                    $('#textInput').focus();
                    $(input).blur(function(item){
                        var txt = $.trim($(input).val());
                        $(input).remove();
                        if(txt.length > 0){
                            obj.font = setFont;
                            obj.lineWidth = 1;
                            obj.fillStyle = "#f00";
                            obj.fillText( txt,resetX,resetY);
                            arr.push(obj.getImageData(0,0,width,height));
                        }
                    })
                }
            }
        }
    }
}
//画图工具选择
function chooseTool(item,num){
    if(num != 5){
        if($(item).hasClass('toolActive')){
            Msg('当前为选中状态',5);
        }else{
            $(item).addClass('toolActive').siblings().removeClass('toolActive');
        }
    }
}